<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import echarts from 'echarts'

  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      pieData: {
        type: Object,
        required: true
      },
      pieName: {
        type: String,
        default: '注册来源比例'
      }
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      pieData: {
        deep: true,
        handler(val) {
          this.setOptions(val);
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons');
        this.setOptions(this.pieData);
      },
      setOptions({legendData, seriesData, colorData} = {}) {
        let mylabel = {
          show: true,
          position: "right",            //标签的位置。// 绝对的像素值[10, 10],// 相对的百分比['50%', '50%'].'top','left','right','bottom','inside','insideLeft','insideRight','insideTop','insideBottom','insideTopLeft','insideBottomLeft','insideTopRight','insideBottomRight'
          offset: [30, 40],             //是否对文字进行偏移。默认不偏移。例如：[30, 40] 表示文字在横向上偏移 30，纵向上偏移 40。
          formatter: '{b} : ({d}%)',//标签内容格式器。模板变量有 {a}、{b}、{c}，分别表示系列名，数据名，数据值。
        };
        this.chart.setOption({
          color: colorData,
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            show: false,
            left: 'center',
            bottom: '20',
            data: legendData,
            orient: 'horizontal',
            itemGap: 80
          },
          series: [
            {
              name: this.pieName,
              type: 'pie',
              roseType: 'radius',
              radius: [20, 85],
              center: ['50%', '38%'],
              data: seriesData,
              animationEasing: 'cubicInOut',
              animationDuration: 2600,
              label: {                    //图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等，
                normal: mylabel,
                emphasis: mylabel
              }
            }
          ]
        })
      }
    }
  }
</script>
